// 开发环境
// let baseUrl = 'http://58.56.28.6:3003/';
let baseUrl = "";
// const baseUrl = 'http://192.168.3.52:8088/';

console.log("baseApiUrl global",uni.getStorageSync("baseApiUrl"));
baseUrl = "http://" + uni.getStorageSync("baseApiUrl") + "/";

const uploadHeader = {
	'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0'
}
import qs from 'qs';

//带Token请求
const httpRequest = (opts = {
	url: "",
	method: "post",
	loading: false,
	requestHeader: {},
	complete: (result) => {}
}, data) => {

	if (!networkStatusChange()) {
		return false;
	}
    
    if(opts.url != "" && opts.url != null && opts.url != undefined){
	
        opts.params = opts.params || {};
        const params = qs.stringify(opts.params)
        if (params !== '') {
            opts.url = opts.url + '?' + params
        }
        opts.complete = opts.complete ? opts.complete : (result) => {};
        if (opts.loading) {
            // uni.showLoading({
            // 	title: "请稍等"
            // })
        }
		
		console.log("request userInfo",uni.getStorageSync("userInfo"));
		console.log("request userInfo data",data);
		//统一在请求参数中添加seat
		if(uni.getStorageSync("userInfo") != undefined && uni.getStorageSync("userInfo") != "" && uni.getStorageSync("userInfo").seat != undefined && uni.getStorageSync("userInfo").seat == opts.params.seat){
			opts.params.seat = uni.getStorageSync("userInfo").seat;
			
			if(data != undefined){
				data.seat = uni.getStorageSync("userInfo").seat;
			}
		}
        
        console.log("request opt",opts,data,uni.getStorageSync("userInfo"));
        
        let current_token = uni.getStorageSync("token");
        console.log("current_token",current_token,current_token.token);

        if((current_token == "" || current_token == null || current_token == undefined) && (!opts.url.includes("getAppVersionInfo")) && !opts.url.includes("login")){
            return false;
        }else{
            console.log("current_token",current_token.token);
            //添加TOKEN，区分APP版本，登录过滤
            if(current_token.token != undefined){
                opts.params.token = current_token.token;
            }else{
                //opts.params.token = "123456";
            }
            
            if(data != undefined && current_token.token != undefined){
                data.token = current_token.token;
            }else{
                //data.token = "123456";
            }
            
            // opts.params.token = "123456";
            // data.token = "123456";
            
            
        }
        
        console.log("request data",data);
        console.log("request params",opts.params);

        let header = {
            'X-Requested-With': 'XMLHttpRequest',
            'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
            "Accept": "application/json",
            "Content-Type": "application/json; charset=UTF-8",
        }
        if (opts.requestHeader) {
            header = Object.assign({}, header, opts.requestHeader);
        }

        let promise = new Promise(function(resolve, reject) {
            // console.log(baseUrl + opts.url, data);
            let httpDefaultOpts = {
                url: opts.url,
                data: data,
                method: opts.method,
                params: (Array.isArray(opts.params) && opts.params.length === 0) ? data : opts.params,
                header: header,
                dataType: 'json',
                success: (res) => {
                    console.log("request success:",res);

                    opts.complete(res);
                    
                    switch (res.data.code) {
                        case 200:
                            resolve(res)
                            break;
                        case 5000:
                            uni.reLaunch({
                                url: '/pages/login/index'
                            });
                            uni.clearStorageSync();
                            break;
                        case 500:
                            uni.showToast({
                                title: res.data.msg,
                                duration: 2000,
                                icon: "none"
                            });
							
                            return false
                            break;

                        case 205:
                            //清除TOKEN
                            uni.setStorageSync("token","");
                        
                            goLogin(opts.url,res.data.msg);
                            
                            break;
                        default:
                            resolve(res)
                            break;
                    }
                },
                fail: (err) => {
                    console.log("request fail:",err);
                    if(err.errMsg = "request:fail abort statusCode:-1 timeout"){
                        uni.showToast({
                            title: "请求超时",
                            duration: 2000,
                            icon: "error"
                        });
                    }
                    if (opts.loading) {
                        uni.hideLoading()
                    }
                    reject(err)
                },
                complete: (err) => {
                    console.log("request complete:",err);
                    if (opts.loading) {
                        uni.hideLoading()
                    }
                }
            }

            uni.request(httpDefaultOpts);
        })
        return promise
        // let token = uni.getStorageSync('token')
        //此token是登录成功后后台返回保存在storage中的
    }
};

// 拦截器
const hadToken = () => {
	// let token = uni.getStorageSync('token');

	// if (token == '' || token == undefined || token == null) {
	// 	goLogin();
	// 	return false;
	// }
	// return token;
}
const networkStatusChange = () => {
	uni.onNetworkStatusChange(function(res) {
		if (!res.isConnected) {
			uni.showToast({
				title: '网络连接不可用！',
				icon: 'none'
			});
			return false
		}
	});
	return true;
}

const goLogin = (data,msg) => {
    if(data.includes("AppIndexNew/login")){
        uni.showToast({
            title: msg == "" ? '账号已到期，请先充值':msg,
            icon: 'none',
            duration: 3000
        });
    }else{
        uni.showToast({
            title: msg == "" ? '账号已到期，请先充值':msg,
            icon: 'none',
            duration: 3000,
            complete: function() {
                uni.reLaunch({
                    url: '/pages/index/login'
                });
            }
        });
    }
    
    // //清除TOKEN
    // uni.setStorageSync("token","");
    
	return false;
}
export default {
	baseUrl,
	httpRequest,
	hadToken,
	uploadHeader
}